<template>
  <div class="annotation-container">
    <!-- 左侧菜单 -->
    <AnnotationMenu
      :menuList="menuList"
      @handle-menu="handleMenu"
      @handle-back="handleBack"
      :activeRule="(item) => !!(item.key == mouseOperationType)"
    />

    <div class="annotation-container-center-right">
      <template v-if="fileUrl">
        <div class="annotation-container-center">
          <!-- 头部标注操作 -->
          <AnnotationOperation
            ref="annotationOperationRef"
            :detailMsg="detailMsg"
            :operationList="operationList"
            :batchOperationRectKeyList="batchOperationRectKeyList"
            @handle-operation="handleOperation"
          />

          <!-- 标注区域 -->
          <Annotation
            ref="annotationRef"
            v-model:data="rectList"
            v-model:batchRectList="batchRectList"
            v-model:mouseOperationType="mouseOperationType"
            v-model:imageScale="imageScale"
            :srcUrl="fileUrl"
            :shortcutConfig="shortcutConfig"
            @mouseenter="blurAllInputs"
          />
        </div>
        <div class="annotation-container-right">
          <div class="annotation-container-right-search">
            <el-input :prefix-icon="Search" v-model="searchText" placeholder="请输入项目名称" />
            <!-- <el-icon style="margin-left: 8px"><Search /></el-icon> -->
          </div>
          <div class="rect-list">
            <div
              v-for="(item, index) in rectList"
              v-show="!searchText || (searchText && item?.fieldName?.includes(searchText))"
              class="rect-item"
              :key="item.id"
              :style="[
                (item.id == selectedElementId || batchOperationRectKeyList?.includes(item.id)) &&
                  getSelectStyle(item, batchOperationRectKeyList?.includes(item.id))
              ]"
              @mouseenter="handleMouseEnter(item)"
              @click="handleClick(item)"
            >
              <div class="rect-item-header">
                <span>#{{ index + 1 }}</span>

                <!-- <el-dropdown placement="bottom-end" @command="handleDropdownCommand"> -->
                <el-dropdown placement="bottom-end" @command="handleDropdownCommand">
                  <!-- <el-icon style="cursor: pointer"><More /></el-icon> -->
                  <span class="iconfont icon-dengdai_icon" style="cursor: pointer"></span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item :command="{ type: 'remove', item }">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
              <div class="rect-item-field">
                <div class="field-name">字段名称</div>
                <el-input
                  autosize
                  type="textarea"
                  resize="none"
                  @click.stop
                  v-model="rectList[index].fieldName"
                />
              </div>
              <div class="rect-item-field">
                <div class="field-name">格式处理</div>
                <el-select
                  @click.stop
                  v-model="rectList[index].formatType"
                  placeholder="请选择"
                  :show-arrow="false"
                  style="width: 100%"
                >
                  <el-option
                    v-for="formatItem in formatProcessingList"
                    :key="formatItem.value"
                    :label="formatItem.label"
                    :value="formatItem.value"
                  />
                </el-select>
              </div>

              <div class="rect-item-field">
                <div class="field-name">测试结果</div>
                <el-input
                  autosize
                  type="textarea"
                  resize="none"
                  @click.stop
                  v-model="rectList[index].result"
                />
              </div>
            </div>
          </div>
          <div class="annotation-container-right-bottom">
            <el-button
              class="annotation-container-right-bottom-btn annotation-container-right-bottom-test-btn"
            >
              批量测试
            </el-button>

            <el-button
              class="annotation-container-right-bottom-btn annotation-container-right-bottom-save-btn"
              @click="save"
            >
              保存
            </el-button>
          </div>
        </div>
      </template>
      <AnnotationUploadFile
        v-else
        ref="fileUploadRef"
        class="file-upload"
        @file-selected="handleFileSelected"
        desc1="ドラッグ＆ドロップ/クリック/コピーによるアップロードをサポート"
        desc2="アップロードされた資料は本回の識別効果テストのみに使用し、第三者に提供することはありません。"
        :http-request="handleUpload"
        accept=".png,.jpg,.jpeg,.pdf"
      >
        <!-- <template #default="{ file }">
          <div class="custom-uploaded-file">
            <h4 style="text-align: center">アップロード成功</h4>
            <p>ファイル名：{{ file.name }}</p>
          </div>
        </template> -->
      </AnnotationUploadFile>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, computed, onMounted } from 'vue'
import Annotation from '@/components/Annotation/index.vue'
import AnnotationOperation from './components/annotation-operation.vue'
// import Annotation from '@/components/Annotation/originIndex.vue'
// import Annotation from "@/components/annotation copy.vue";
import { Search, More, Expand, Fold } from '@element-plus/icons-vue'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// import { uploadFile, uploadPdfFile } from '@/api/annotation'
// const { t } = useI18n()
const t = (key) => key;
function hexToRgb(hex, alpha = 0.1) {
  // 去除可能存在的 # 前缀
  hex = hex.replace(/^#/, '')

  // 处理简写形式，如 #fff
  if (hex.length === 3) {
    hex = hex
      .split('')
      .map((c) => c + c)
      .join('')
  }

  // 解析十六进制值
  const bigint = parseInt(hex, 16)
  const r = (bigint >> 16) & 255
  const g = (bigint >> 8) & 255
  const b = bigint & 255

  // 返回 rgba 格式字符串
  return `rgba(${r}, ${g}, ${b}, ${alpha})`
}
// const fileUrl = ref('@/assets/test/cc.jpg')
// const fileUrl = ref('')
const fileUrl = ref("@/assets/row.png");
// import Annotation from "@/components/annotation-origin.vue";
const mouseOperationType = ref('mouseSelect')
// const mouseOperationType = ref('batchSelect')
const batchRectList = ref(new Map())
const imageScale = ref(1)
const annotationRef = ref(null)

const detailMsg = ref({
  id: '',
  projectName: '项目名称',
  templateName: '模板名称',
  currentCount: 1,
  allCount: 10
})
const shortcutConfig = ref({
  readRangeMarker: {
    key: 'n',
    fill: '#ef4c4c'
  },
  unReadRangeMarker: {
    key: 'r',
    fill: '#40ff40'
  }
})
const isExpanded = ref(true)

const menuList = ref([
  {
    key: 'mouseSelect',
    name: t('annotation.mouseSelect'),
    icon: 'shubiaoxuanze_icon',
    showActive: true
  },
  {
    key: 'batchSelect',
    name: t('annotation.batchSelect'),
    icon: 'piliangxuanze_icon',
    showActive: true
  },
  {
    key: 'standardSetting',
    name: t('annotation.standardSetting'),
    icon: 'biaozhunshezhi_icon',
    showActive: false
  },
  {
    key: 'exportSetting',
    name: t('annotation.exportSetting'),
    icon: 'daochushezhi_icon',
    showActive: false
  },
  {
    key: 'outputSetting',
    name: t('annotation.outputSetting'),
    icon: 'chulixiangmushezhi_icon',
    showActive: false
  },
  {
    key: 'templateDownload',
    name: t('annotation.templateDownload'),
    icon: 'mobanxiazai_icon',
    showActive: false
  }
])
const iconMap = ElementPlusIconsVue
const operationList = ref([
  // {
  //   key: 'prev',
  //   name: t('annotation.prev'),
  //   icon: ''
  // },
  // {
  //   key: 'next',

  //   name: t('annotation.next'),
  //   icon: ''
  // },
  {
    key: 'reset',
    name: t('annotation.reset'),
    icon: 'FullScreen',
    style: {
      marginRight: '16px'
    }
  },
  {
    key: 'revoke',
    name: t('annotation.revoke'),
    icon: 'RefreshLeft'
  },
  {
    key: 'cancelRevoke',
    name: t('annotation.cancelRevoke'),
    icon: 'RefreshRight',
    style: {
      marginRight: '16px'
    }
  },

  {
    key: 'magnify',
    name: t('annotation.magnify'),
    icon: 'ZoomIn'
  },
  {
    key: 'reduce',
    name: t('annotation.reduce'),
    icon: 'ZoomOut'
  }
  // {
  //   key: 'intro',
  //   name: t('annotation.intro'),
  //   icon: ''
  // }
])

const formatProcessingList = ref([
  {
    label: '格式处理1',
    value: '1'
  },
  {
    label: '格式处理2',
    value: '2'
  },
  {
    label: '格式处理3',
    value: '3'
  }
])
const searchText = ref('')

const batchOperationRectKeyList = computed(() => {
  const keyList = []
  if (batchRectList.value?.size) {
    batchRectList.value.forEach((_, key) => {
      keyList.push(key)
    })
  }
  return keyList
})

// const filterRectList = computed(() => {
//   if (searchText.value) {
//     return rectList.value.filter((item) => item.label.includes(searchText.value));
//   }
//   return rectList.value;
// });
function getSelectStyle(rectItem, isBatchSelect) {
  return {
    background: hexToRgb(shortcutConfig.value[rectItem.rectType].fill, isBatchSelect ? 0.4 : 0.1),
    borderColor: shortcutConfig.value[rectItem.rectType].fill
  }
}

const handleUpload = async (file) => {
  // 判断文件是否为 PDF
  let response
  // if (file.type === 'application/pdf') {
  //   // 假设 uploadFile 函数支持额外参数，这里添加一个 PDF 标记参数
  //   response = await uploadPdfFile(file)
  // } else {
  //   response = await uploadFile(file)
  // }
  // // const response = await uploadFile(file)
  // const fileUrl = response
  // console.log('fileUrl--', fileUrl)

  // return fileUrl
}

const handleFileSelected = async ({ file, fileUrl: url, name }) => {
  console.log('handleFileSelected', file)
  console.log('url--', url)

  fileUrl.value = url
}

const rectList = ref([])

onMounted(() => {
  console.log('rectList.value--', rectList.value)
  setTimeout(() => {
    rectList.value = JSON.parse(localStorage.getItem('rectList')) || [
      {
        type: 'rect',
        id: 'element_1755409174402_nhce73bx6',
        rectType: 'readRangeMarker',
        x: 0,
        y: 0,
        width: 436,
        height: 241,
        fieldName: '',
        desc: '',
        formatType: '',
        result: '',
        position: [0, 152, 625.640625, 152, 625.640625, 393, 0, 393]
      },
      {
        type: 'rect',
        id: 'element_1755409174402_nhce73bx61',
        rectType: 'readRangeMarker',
        x: 2027.60107421875,
        y: 220.81103515625,
        width: 2397.430908203125 - 2027.60107421875,
        height: 70,
        fieldName: '',
        desc: '',
        formatType: '',
        result: '',
        position: [
          2027.60107421875, 220.81103515625, 2397.430908203125, 221.28485107421875,
          2396.90185546875, 297.56475830078125, 2027.1673583984375, 297.0493469238281
        ]
      },
      {
        type: 'rect',
        id: 'element_1755409174402_nhce73bx62',
        rectType: 'readRangeMarker',
        x: 468.2182922363281,
        y: 305.75103759765625,
        width: 1094.1683349609375 - 468.2182922363281,
        height: 395.3443603515625 - 305.75103759765625,
        fieldName: '',
        desc: '',
        formatType: '',
        result: '',
        position: [
          468.2182922363281, 305.75103759765625, 1094.1683349609375, 306.63372802734375,
          1093.9405517578125, 396.30999755859375, 468.17987060546875, 395.3443603515625
        ]
      }
    ]
  }, 0)
})

// 鼠标移入选中当前矩形
const handleMouseEnter = (item) => {
  const hoverElement = annotationRef.value.allElements.find(
    (ele) => ele.data('elementId') == item.id
  )
  // console.log('hoverElement--', hoverElement)
  annotationRef.value.handleHoverPreview(
    {
      x: item.x,
      y: item.y
    },
    hoverElement
  )
}

const handleClick = (item) => {
  if (mouseOperationType.value == 'batchSelect') {
    annotationRef.value.handlerBatchRectList(item)
  }
}

const handleDropdownCommand = (command) => {
  if (command.type == 'remove') {
    annotationRef.value?.removeElement(command.item.id)
  }
}

const selectedElementId = computed(() => {
  return annotationRef.value?.hoveredElement?.data('elementId')
})

const handleMenu = (item) => {
  if (!fileUrl.value) {
    ElMessage.error(t('annotation.uploadImage'))
    return
  }
  if (item.key == 'mouseSelect') {
    mouseOperationType.value = 'mouseSelect'
    annotationRef.value?.clearBatchOperationRectList()
  } else if (item.key == 'batchSelect') {
    mouseOperationType.value = 'batchSelect'
  } else {
    // mouseOperationType.value = ''
    switch (item.key) {
      case 'standardSetting':
        console.log('标准设置')
        break
      case 'exportSetting':
        console.log('导出设置')
        break
      case 'outputSetting':
        console.log('输出设置')
        break
      case 'templateDownload':
        console.log('模板下载')
        break

      default:
        break
    }
  }
}

function handleBack() {
  console.log('返回')
}

const handlePrev = () => {
  console.log('上一张')
}
const handleNext = () => {
  console.log('下一张')
}

const handleOperation = (item) => {
  switch (item.key) {
    case 'prev':
      console.log('切换')

      break
    case 'next':
      break
    case 'intro':
      break
    case 'revoke':
      undoLastAction()
      break
    case 'cancelRevoke':
      cancelUndo()
      break
    case 'magnify':
      annotationRef.value?.changeScale('magnify')
      break
    case 'reduce':
      annotationRef.value?.changeScale('reduce')
      break
    case 'reset':
      annotationRef.value?.resetViewport()
      break
    default:
      break
  }
}

watch(
  () => rectList.value,
  (newVal) => {
    console.log('newVal---', newVal)
  },
  { immediate: true, deep: true }
)

const hasHistory = computed(() => {
  return hasUndoStack.value || hasRedoStack.value
})
const hasUndoStack = computed(() => {
  return !!annotationRef.value?.historyOperationList?.undoStack?.length
})
const hasRedoStack = computed(() => {
  return !!annotationRef.value?.historyOperationList?.redoStack?.length
})

const undoLastAction = () => {
  if (hasUndoStack.value) {
    annotationRef.value.undoLastAction()
  }
}
const cancelUndo = () => {
  if (hasRedoStack.value) {
    annotationRef.value.cancelUndo()
  }
}

// 添加函数用于取消所有输入框的聚焦状态
const blurAllInputs = () => {
  const inputs = document.querySelectorAll('input, select')
  inputs.forEach((input) => input.blur())
}

const save = () => {
  const saveData = rectList.value.map((item) => {
    return {
      ...item,
      x: item.x / imageScale.value,
      y: item.y / imageScale.value,
      width: item.width / imageScale.value,
      height: item.height / imageScale.value
    }
  })
  localStorage.setItem('rectList', JSON.stringify(saveData))

  console.log('saveData--', saveData)
}
</script>
<style lang="scss" scoped>
.annotation-container {
  height: 100%;
  display: flex;
  // overflow-x: auto;
}

.annotation-container-center-right {
  flex: 1;
  display: flex;
  overflow-x: auto;
}
.annotation-container-center {
  flex: 1;
  background-color: #ffffff;
  display: flex;
  flex-direction: column;
  min-width: 900px;
  padding-bottom: 48px;
}
.annotation-container-right {
  // width: 280px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #fff;
  // padding: 12px;
  overflow-y: hidden;
  border-left: 1px solid #d1d5db;
  width: 17%;
  min-width: 280px;
  .annotation-container-right-search {
    display: flex;
    align-items: center;
    height: 48px;
    padding: 4px 12px;
    border: 1px solid #f5f5f5;
  }
}

.rect-list {
  flex: 1;
  overflow-y: auto;
  padding: 12px 12px 12px;
  .rect-item {
    border-radius: 8px;
    margin-bottom: 8px;
    padding: 12px;
    color: #515866;

    background: #ffffff;
    border-radius: 8px;
    border: 1px solid #f5f5f5;

    .rect-item-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .rect-item-field {
      margin-bottom: 8px;
    }
    .field-name {
      font-weight: 400;
      font-size: 14px;
      color: #535862;
      line-height: 22px;
    }

    .label {
      color: #424b5a;
    }
    .value {
      color: #606266;
    }
  }
}

.annotation-container-right-bottom {
  display: flex;
  // padding: 12px;
  align-items: center;
  justify-content: flex-end;
  border-top: 1px solid #d1d5db;
  padding-right: 12px;
  height: 48px;

  .annotation-container-right-bottom-btn {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 6px;
    border-radius: 4px;
    cursor: pointer;
    // flex-shrink: 0;
    // flex: none !important;
    // width: max-content;
    padding: 0 16px;
    // margin-right: 0 !important;
  }
  .annotation-container-right-bottom-test-btn {
    // flex: 1;
    background: #fff;
    border: 1px solid #3662ec;
    color: #3662ec;
    // margin-right: 10px;
  }
  .annotation-container-right-bottom-save-btn {
    // flex: 1;
    background: #3662ec;
    color: #fff;
  }
}
</style>
